<template>
  <el-form
    ref="formRef"
    :model="model"
    label-position="left"
    :rules="rules"
  >
    <el-form-item label="单位" prop="unit_id" :label-width="labelWidth">
      <div>
        <el-select
          v-model="model.unit_id"
          placeholder="请选择"
          @change="handleSelectChange"
        >
          <el-option
            v-for="item in units"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          v-if="model.unit_id"
          style="margin-left: 10px;"
          type="text"
        >
          库存：{{ quantityFormat() }}
        </el-button>
      </div>
    </el-form-item>

    <el-form-item
      v-if="model.unit_id"
      label="调整数量"
      prop="adjust_quantity"
      :label-width="labelWidth"
    >
      <div style="display: flex;">
        <el-input-number
          v-model="model.adjust_quantity"
          :min="adjustMinQuantity"
          :max="10000"
          placeholder="请输入调整数量"
        />

        <el-button type="text" style="margin-left: 10px;">
          {{ currentUnit?.label }}
        </el-button>
      </div>
    </el-form-item>

    <el-form-item label="调整原因" prop="reason" :label-width="labelWidth">
      <el-input
        v-model="model.reason"
        type="textarea"
        maxlength="200"
        show-word-limit
        placeholder="请输入调整原因"
      />
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: '',
  props: {
    model: {
      type: Object,
      default: () => ({})
    },

    currentGoodsQuantity: {
      type: Number,
      default: 0
    },

    unitList: {
      type: Array,
      default: () => []
    }

  },
  data() {
    return {
      labelWidth: '80px',
      rules: {
        unit_id: [
          { required: true, message: '请选择单位', trigger: ['change', 'blur'] }
        ],
        adjust_quantity: [
          { required: true, message: '请输入调整数量', trigger: ['change', 'blur'] },
          {
            validator: (rule, value, callback) => {
              if (value === 0) return callback('请输入有效的调整数量')
              const total = value * this.currentUnit?.conversion_ratio
              if (total < this.currentGoodsQuantity * -1) {
                return callback('调整数量超出库存量')
              }

              callback()
            }
          }
        ],

        reason: [
          { required: true, message: '请输入调整原因', trigger: ['change', 'blur'] }
        ]
      }
    }
  },

  computed: {
    units() {
      return this.unitList.map(unit => {
        return {
          label: unit?.name,
          value: unit.id,
          conversion_ratio: unit.conversion_ratio
        }
      })
    },

    mainUnit() {
      return this.unitList.find(item => item.is_main)
    },

    currentUnit() {
      if (!this.model.unit_id) return null
      return this.units.find(item => item.value === this.model.unit_id)
    },

    adjustMinQuantity() {
      const quantity = this.currentGoodsQuantity
      if (quantity <= 0) return 1
      const conversionRation = this.currentUnit.conversion_ratio
      const boxes = Math.floor(quantity / conversionRation)
      return boxes * -1
    }
  },

  methods: {
    validate() {
      return new Promise(resolve => {
        this.$refs.formRef.validate(flag => {
          resolve(flag)
        })
      })
    },

    resetFields() {
      this.$refs.formRef.resetFields()
    },

    handleSelectChange(e) {
      this.$refs.formRef.validateField('adjust_quantity')
    },

    quantityFormat() {
      const quantity = this.currentGoodsQuantity
      const { conversion_ratio, label: currentUnitName, value: currentUnitId } = this.currentUnit
      const { name: mainName, id: mainId } = this.mainUnit

      const boxes = Math.floor(quantity / conversion_ratio)
      const remaining = Math.round((quantity / conversion_ratio - boxes) * conversion_ratio)

      if (currentUnitId === mainId) return `${boxes}${currentUnitName}`
      return `${boxes}${currentUnitName} ${remaining}${mainName}`
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
